package com.ruoyi.web.controller.orders;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.shop.domain.Shop;
import com.ruoyi.shop.service.IShopService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.orders.domain.Orders;
import com.ruoyi.orders.service.IOrdersService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订单管理Controller
 * 
 * @author admin
 * @date 2025-05-20
 */
@RestController
@RequestMapping("/orders/orders")
public class OrdersController extends BaseController
{
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IShopService shopService;
    /**
     * 查询订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('orders:orders:list')")
    @GetMapping("/list")
    public TableDataInfo list(Orders orders)
    {
        startPage();


        List<Orders> list = ordersService.selectOrdersList(orders);
        return getDataTable(list);
    }

    /**
     * 导出订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('orders:orders:export')")
    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Orders orders)
    {
        List<Orders> list = ordersService.selectOrdersList(orders);
        ExcelUtil<Orders> util = new ExcelUtil<Orders>(Orders.class);
        util.exportExcel(response, list, "订单管理数据");
    }

    /**
     * 获取订单管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('orders:orders:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(ordersService.selectOrdersById(id));
    }

    /**
     * 新增订单管理
     */
    @PreAuthorize("@ss.hasPermi('orders:orders:add')")
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Orders orders)
    {
        return toAjax(ordersService.insertOrders(orders));
    }

    /**
     * 修改订单管理
     */
    @PreAuthorize("@ss.hasPermi('orders:orders:edit')")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Orders orders)
    {
        return toAjax(ordersService.updateOrders(orders));
    }

    /**
     * 删除订单管理
     */
    @PreAuthorize("@ss.hasPermi('orders:orders:remove')")
    @Log(title = "订单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(ordersService.deleteOrdersByIds(ids));
    }
//订单预约新增
    @PostMapping("/submit")
    public  AjaxResult  addOrders(@RequestBody Orders orders){
        LocalDateTime localDateTime = LocalDateTime.now();

        // 转换为 Date
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());



        orders.setTypeId(1L);
        Long userId = SecurityUtils.getUserId();

        orders.setUserId(userId);
        orders.setAccount(orders.getOriginalPrice());
        orders.setStatus(1L);
        orders.setPayTime(date);
        orders.setPayStatus(0L);
        int rows = ordersService.insertOrders(orders);
        if (rows > 0) {
            // 插入成功后，orders对象的id属性会被MyBatis自动填充
            return AjaxResult.success("操作成功", orders.getId());
        }
        return AjaxResult.error("操作失败");

    }
//   获取当前当前用户的订单
    @GetMapping("/listByUserId")
    public TableDataInfo listByUserId(){
        Orders orders = new Orders();
        Long userId = SecurityUtils.getUserId();
        orders.setUserId(userId);

        return getDataTable( ordersService.selectOrdersList(orders));
    }
//  处理订单
    @PutMapping("/change")
    public AjaxResult changeStatus(@RequestBody Orders orders){
        Long id = orders.getId();
        Orders orders1 = ordersService.selectOrdersById(id);
        orders1.setPayStatus(orders.getPayStatus());
        System.out.println(orders1);
        return toAjax(ordersService.updateOrders(orders1));
    }
//    新增商品订单
    @PostMapping("/addShopOrder")
    public AjaxResult addShopOrder(@RequestBody Orders orders){
//        当前用户id
        Long userId = SecurityUtils.getUserId();
//        当前时间
        LocalDateTime localDateTime = LocalDateTime.now();

        // 转换为 Date
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        Long shopId = orders.getProjectId();
//        System.out.println(orders);
        Shop shop = shopService.selectShopById(shopId);
        String name = shop.getName();
        BigDecimal price = shop.getPrice();
        orders.setTypeId(2L);
        orders.setUserId(userId);
        orders.setCreateTime(date);
        orders.setUpdateTime(date);
        orders.setPayTime(date);
        orders.setPayStatus(1L);
        orders.setOriginalPrice(price);
        orders.setAccount(price);
        orders.setName(name);
        orders.setStatus(1L);
//        商品库存
        Long inventory = shop.getInventory();
        shop.setInventory(inventory-1);
        shopService.updateShop(shop);
//        System.out.println(orders);
        return toAjax(ordersService.insertOrders(orders));
    }
//    新增会员卡
    @PostMapping("/addCardOrder")
public AjaxResult addCardOrder(@RequestBody Orders orders) {
    Long userId = SecurityUtils.getUserId();
    //        当前时间
    LocalDateTime localDateTime = LocalDateTime.now();

    // 转换为 Date
    Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    BigDecimal price = orders.getOriginalPrice();
    orders.setUserId(userId);
    orders.setTypeId(3L);
    orders.setUserId(userId);
    orders.setCreateTime(date);
    orders.setUpdateTime(date);
    orders.setPayTime(date);
    orders.setPayStatus(1L);
    orders.setOriginalPrice(price);
    orders.setAccount(price);
    orders.setStatus(1L);
    return toAjax(ordersService.insertOrders(orders));
}
}
